package com.asiainfo.dacp.datastash.open.controller;

import com.asiainfo.dacp.datastash.domain.unit.models.DataStashUnit;
import com.asiainfo.dacp.datastash.domain.unit.repos.DataStashUnitRepository;
import com.asiainfo.dacp.web.SessionKeyConstants;
import com.asiainfo.dacp.web.models.User;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by winter on 2017/10/31.
 */
@RestController
@RequestMapping("/open/datastash")
@Api(tags={"datastash-unit"},value="单元")
public class DataStashUnitController {

    @Autowired
    private DataStashUnitRepository dataStashUnitRepository;

    @RequestMapping(value = "unit/creator", method = RequestMethod.POST)
    @ApiOperation(tags = {"unit"}, value = "创建单元")
    public Map unitCreator(@RequestBody String unitBody, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        Map responseMessage = new HashMap();
        responseMessage.put("success", true);
        String responseBody = null;
        DataStashUnit unit =null;
        try{
            unit = new Gson().fromJson(unitBody,DataStashUnit.class);
        }catch(RuntimeException e){
            e.printStackTrace();
            throw e;
        }
        User user = (User) request.getSession().getAttribute(SessionKeyConstants.USER);
        if(user!=null){
            String userId = user.getId();
            unit.setCreateUser(userId);
        }

        try {
            unit=dataStashUnitRepository.save(unit);
            responseMessage.put("unit",unit);
        } catch (Exception e) {
            e.printStackTrace();
            responseBody = "操作失败！"+e.getMessage();
            responseMessage.put("msg", responseBody);
            responseMessage.put("success", false);
        }
        return responseMessage;
    }


    @RequestMapping(value = "unit/{id}", method = RequestMethod.GET)
    @ApiOperation(tags = {"unit"}, value = "查询单元")
    public DataStashUnit unitQuery( @PathVariable String id, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        return dataStashUnitRepository.findOne(id);
    }

    @RequestMapping(value = "unit/code/{code}", method = RequestMethod.GET)
    @ApiOperation(tags = {"unit"}, value = "单元存在判断")
    public DataStashUnit unitQueryByCode( @PathVariable String code, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        return dataStashUnitRepository.findByCode(code);
    }

    @RequestMapping(value = "unit/{id}/delete", method = RequestMethod.POST)
    @ApiOperation(tags = {"unit"}, value = "删除单元")
    public Map unitDelete(@PathVariable String id, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        String responseBody = null;
        Map responseMessage = new HashMap();
        responseMessage.put("success", true);
        try {
            dataStashUnitRepository.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            responseBody = "操作失败！"+e.getMessage();
            responseMessage.put("msg", responseBody);
            responseMessage.put("success", false);
        }
        return responseMessage;
    }
    
    @RequestMapping(value = "unit/{oper}/{id}", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> publish(@PathVariable("oper") String oper,@PathVariable("id") String id) {
        String responseBody="";
        Map responseMessage = new HashMap();
        responseMessage.put("success", true);
        try {
            if(oper.equals("publish") ){
                dataStashUnitRepository.updateState(id,"3");
            }else if(oper.equals("online")){
                dataStashUnitRepository.updateState(id,"1");
            }else if(oper.equals("offlineApply")){
                dataStashUnitRepository.updateState(id,"4");
            }else if(oper.equals("offline")){
                dataStashUnitRepository.updateState(id,"2");
            }
            responseBody = "操作成功！";
            responseMessage.put("msg", id);
        } catch (Exception e) {
            e.printStackTrace();
            responseBody = "操作失败！"+e.getMessage();
            responseMessage.put("msg", responseBody);
            responseMessage.put("success", false);
        }
        return responseMessage;
    }


    @RequestMapping(value = "", method = RequestMethod.GET)
    public
    Page<DataStashUnit> getDataDefines(
            @RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "unitCode", defaultValue = "") String unitCode,
            @RequestParam(value = "label", defaultValue = "") String label,
            @RequestParam(value = "unitType", defaultValue = "") String unitType,
            @RequestParam(value = "state",defaultValue = "") String state,
            @RequestParam(value = "id", defaultValue = "") String id)throws Exception {
        Page<DataStashUnit> pageList = dataStashUnitRepository.findAll(pageSize, pageNum,unitCode,id,label, unitType, StringUtils.isEmpty(state)?null:state.split(","));
        return pageList;
    }
}